﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Device.Location;
using System.Windows.Threading;

namespace Quebec.Phone.Utilities
{
	public class GpsUtilities
	{
		public static GeoCoordinate GetCurrentPosition()
		{
			GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
			GeoCoordinate coordinate = null;
			bool run = false;

			if (watcher == null)
			{
				watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Use high accuracy.
				watcher.MovementThreshold = 20; // Use MovementThreshold to ignore noise in the signal.
				watcher.StatusChanged += (se, ea) =>
					{
						if (ea.Status == GeoPositionStatus.Ready)
						{
							coordinate = watcher.Position.Location;
							watcher.Stop();
						}
					};
			}

			DispatcherTimer timer = new DispatcherTimer();
			timer.Interval = TimeSpan.FromSeconds(10);
			timer.Tick += (se, ea) =>
			{
				timer.Stop();
				if (watcher != null)
				{
					watcher.Stop();
					watcher = null;
					run = false;
				}
			};
			timer.Start();

			watcher.Start();
			run = true;

			while (run)
			{
				return coordinate;
			}

			return null;
		}
	}
}
